<script setup lang="ts">
import type { TreeInstance } from 'element-plus-cisdi';
import type { LoadFunction, TreeNodeData } from 'element-plus-cisdi/es/components/tree/src/tree.type';
import type { DataTypes, OrgBo, OrgUserBO, UserBO, UserMapValue } from '@/model/UserBo';
import type { AddRoleParams, DeleteRoleParams, GetRoleListParams, GetUserRoleListParams } from '@/model/UserRoleBo';
import { OrgUserTransfer, OrgUserTransfer_TreeDataType, OrgUserTransfer_UserType } from '@minmetals-ui/biz-components';
import { HeaderConfig } from '@minmetals/auth-lib';
import { ElButton, ElCol, ElDialog, ElDivider, ElDropdown, ElDropdownItem, ElDropdownMenu, ElForm, ElFormItem, ElInput, ElMessage, ElPagination, ElRow, ElTable, ElTableColumn, ElTooltip, ElTree } from 'element-plus-cisdi';
import { debounce } from 'lodash-es';
import { computed, reactive, ref, watch } from 'vue';
import empty from '@/components/empty/index.vue';
import { OrgTreeLeafType, UserGender, UserStatus, UserTableColProp } from '@/constants/UserManage';
import { t } from '@/locales';
import { UserRoleService } from '@/services/UserRoleService';
import { UserService } from '@/services/UserService';
import { getHighLight } from '@/utils/HighLightTextUtil';
import { formatTimestampToLocalDateString } from '@/utils/TimeFormatUtil';
import UserExtendInfo from './components/UserExtendInfo.vue';
import UserOrgInfo from './components/UserOrgInfo.vue';
import UserRoles from './components/UserRoles.vue';
import styles from './index.module.scss';

defineOptions({
  name: 'UserManager',
});

const orgForm = reactive({
  orgCode: '',
  orgName: '',
  orgFullName: '',
  orgType: 'org', // 默认非扩展组织
});

// 保存搜索前的orgForm状态
const cachedOrgFormBeforeSearch = ref({ ...orgForm });

// 树实例
const treeRef = ref<TreeInstance | null>(null);
// 父节点编号
const parentId = ref('');
// 树当前选中节点
const currentNodeKey = ref('');
// 存储默认展开的节点 key
const defaultExpandedKeys = ref<string[]>([]);
// 搜索关键词
const filterText = ref('');
const props = {
  isLeaf: (data: TreeNodeData) => {
    // 0 表示叶子节点，1 表示非叶子节点
    return data.isLeaf === OrgTreeLeafType.ORG_IS_LEAF_NUM || data.isLeaf === OrgTreeLeafType.ORG_IS_LEAF_STR;
  },
};
// 搜索状态
const filterStatus = ref(false);
// const filterStatus = computed(() => {
//   return !!filterText.value;
// });

watch(() => filterText.value, (newVal) => {
  if (!newVal) {
    filterStatus.value = false;
  }
});

watch(() => filterText.value, debounce(() => {
  handleSearch();
}, 500));

// 添加存储过滤结果的数据
const searchResults = ref<TreeNodeData[]>([]);
// 当前选中的过滤结果节点
const selectedSearchNode = ref<string>('');
// 数据加载loading
const loading = ref(false);

// 用户搜索内容
const keyWord = ref('');
// 用户列表（完整数据）
const userList = ref<UserBO[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
// 选中的用户数据
const userSelection = ref<UserBO[]>([]);
// 当前行用户数据
const currentUser = ref<UserBO | undefined>();

// 分配角色 弹窗可视状态
const rolesVisible = ref(false);
// 角色信息列表
const rolesList = ref([]);
// 全部的角色列表
const fullRolesList = ref([]);

// 查看组织 弹窗可视状态
const orgVisible = ref(false);
// 组织信息列表
const orgList = ref<OrgBo[]>([]);

// 扩展信息 弹窗可视状态
const infoVisible = ref(false);
// 扩展信息
const infoData = ref('');

// 用户转入 弹窗可视状态
const userInputVisible = ref(false);
// 用户转出-转出至其他组织 弹窗可视状态
const userOutputVisible = ref(false);
// 是否保留原组织关系
const isRetainOrg = ref(true);
// 从本组织中移除用户 弹窗可视状态
const userRemoveVisible = ref(false);
// 转换用户数据
const userVal = ref<DataTypes[] | undefined>([]);
// 转入转出弹窗内接口的请求头信息
const requestParams = ref({
  // replace(/[^\x00-\xFF]/g, '')}
  baseURL: `${import.meta.env.VITE_API_BASE_URL}${import.meta.env.VITE_API_BASE_FOUNDATION}`,
  headers: HeaderConfig.init().getHeaderConfig(),
});

// 下线 弹窗可视状态
const offlineVisible = ref(false);

// 重置密码 弹窗可视状态
const resetPasswordVisible = ref(false);
// 复制密码 信息展示状态
const copyPasswordVisible = ref(false);
// 密码
const password = ref('');

// 用户转出下拉框状态
const userOutputHovering = ref(false);
// 启用下拉框状态
const enabledHovering = ref(false);
// 停用下拉框状态
const disabledHovering = ref(false);
// 更多下拉框状态
const moreHoveringMap = ref<Record<string, boolean>>({});

// 授权用户分页信息
const assignRolesPageInfo = reactive({
  current: 1,
  size: 10,
  total: 0,
});

const fullRolePageInfo = reactive({
  current: 1,
  size: 10,
  total: 0,
});

/**
 * 处理搜索逻辑（仅在 blur/enter 时触发）
 */
async function handleSearch() {
  const keyword = filterText.value?.trim();

  // 关键词为空时，清空结果并返回
  if (!keyword) {
    searchResults.value = [];
    filterStatus.value = false;
    // 清除选中状态
    selectedSearchNode.value = '';

    // 恢复orgForm状态
    Object.assign(orgForm, cachedOrgFormBeforeSearch.value);
    // 重新获取用户列表
    fetchUserList();
    return;
  }

  loading.value = true;
  filterStatus.value = true;
  // 调用搜索接口
  const data = {
    orgCode: 'root',
    isTree: 0,
    loadType: 1,
    keyword,
  };
  const res = await UserService.getOrgTreeOriginalData(data);
  searchResults.value = res.root || [];
  loading.value = false;
}

/**
 * 处理搜索结果项的选中
 * @param node 选中的节点
 */
function handleSelectSearchResult(node: TreeNodeData) {
  // 切换选中状态：如果已选中则取消选中，否则选中该项
  if (selectedSearchNode.value === node.code) {
    selectedSearchNode.value = '';
  } else {
    selectedSearchNode.value = node.code;
  }

  // 调用原有的处理方法
  changeOrgForm(node);
}

/**
 * 逐级加载数据
 * @param node
 * @param resolve
 */
const loadNode: LoadFunction = async (node, resolve) => {
  if (node.level === 0) {
    // 加载根节点
    const data = {
      orgCode: 'root',
      isTree: 1,
      loadType: 0,
    };
    const res = await UserService.getOrgTreeOriginalData(data);
    const rootNodes = res?.root || []; // 根节点列表
    // 若有根节点，默认选中第一个
    if (rootNodes.length > 0) {
      const firstRootNode = rootNodes[0];
      // 选中第一个节点
      changeOrgForm(firstRootNode);
      currentNodeKey.value = firstRootNode.code;

      // 设置默认展开第一个根节点，触发子节点加载
      defaultExpandedKeys.value = [firstRootNode.code];

      // 保存初始状态（只有在非搜索状态下）
      if (!filterStatus.value) {
        cachedOrgFormBeforeSearch.value = { ...orgForm };
      }
    }

    return resolve(rootNodes);
  } else {
    // 加载子节点
    const currentNodeCode = node.data.code.toString();
    currentNodeKey.value = node.data.code.toString();
    parentId.value = currentNodeCode;
    const data = {
      orgCode: parentId.value,
      isTree: 1,
      loadType: 0,
    };
    // 加载子节点方法
    const childrenData = await UserService.getOrgTreeOriginalData(data);
    return resolve(childrenData[currentNodeCode] || []);
  }
};

// 分页改变时
watch([currentPage, pageSize], fetchUserList);

function handleSizeChange(val: number) {
  pageSize.value = val;
}

function handleCurrentChange(val: number) {
  currentPage.value = val;
}

/**
 * 获取用户列表数据
 */
async function fetchUserList() {
  const data = {
    orgCode: orgForm.orgCode,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    keyWord: keyWord.value,
  };
  const res = await UserService.getUserList(data);
  userList.value = res.records || [];
  total.value = +res.total || 0;
}

/**
 * 节点点击事件
 * @param data
 */
function changeOrgForm(data: TreeNodeData) {
  // 节点存在时，走点击和查询用户列表逻辑
  if (JSON.stringify(data) !== '{}') {
    // 点击节点时的处理
    parentId.value = data.code;
    orgForm.orgCode = data.code;
    orgForm.orgName = data.label;
    orgForm.orgFullName = data.orgFullName;
    orgForm.orgType = data.type;

    // 保存当前状态（只有在非搜索状态下才保存）
    if (!filterStatus.value) {
      cachedOrgFormBeforeSearch.value = { ...orgForm };
    }

    fetchUserList();
  }
}

/**
 * 选中变化
 * @param data
 */
function handleCurrentNodeChange(data: TreeNodeData) {
  changeOrgForm(data);
  currentNodeKey.value = data.code;
}

/**
 * 选择行变化
 * @param selection
 */
function handleSelectionChange(selection: UserBO[]) {
  userSelection.value = selection;
  console.log(userSelection.value);
}

/**
 * 时间格式化
 */
function formatDateTime(_: any, __: any, cellValue: any) {
  return cellValue === null ? '-' : formatTimestampToLocalDateString(cellValue);
}

function handleUserInput() {
  userVal.value = undefined;
  userInputVisible.value = true;
  // userVal.value = userSelection.value?.map(item => ({
  //   orgCode: item.orgCode,
  //   userId: item.userId,
  //   label: item.userName,
  //   avatarUrl: '',
  //   fullNamePath: item.fullNamePath,
  //   code: item.orgCode,
  // }))
}

/**
 * 保存用户转入信息
 * @param res
 */
async function saveUserInput(res: OrgUserBO[]) {
  if (res.length === 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  const result = Object.values(
    res.reduce((map: Record<string, UserMapValue>, item: OrgUserBO) => {
      const sourceOrgCode = item.orgCode; // orgCode
      if (map[sourceOrgCode]) {
        // 已存在的分组，追加userIds
        map[sourceOrgCode].userIds += `,${item.userId}`;
      } else {
        // 新分组，只包含两个目标字段
        map[sourceOrgCode] = {
          userIds: item.userId, // 原userId → userIds
          sourceOrgCode, // 原orgId → sourceOrgCode
        };
      }
      return map;
    }, {}),
  );
  const data = {
    items: result,
    targetOrgCode: orgForm.orgCode,
    keepOriginal: isRetainOrg.value ? '1' : '0',
  };
  const response: any = await UserService.transferUsersIn(data);
  if (response) {
    userInputVisible.value = false;
    ElMessage.success(response.message || t('user.userInputSuccess'));
    fetchUserList();
  } else {
    ElMessage.error(response.message || t('user.userInputFail'));
  }
}

/**
 * 取消用户转入
 */
function cancelUserInput() {
  userInputVisible.value = false;
}

function handleUserOut() {
  if (userSelection.value.length === 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  userVal.value = undefined;
  userOutputVisible.value = true;
}

/**
 * 保存用户转出至其他组织信息
 * @param res
 */
async function saveUserOutput(res: TreeNodeData) {
  const result = Object.values(
    userSelection.value.reduce((map: Record<string, UserMapValue>, item: UserBO) => {
      const sourceOrgCode = item.orgCode; // 原parentCode
      if (map[sourceOrgCode]) {
        // 已存在的分组，追加userIds
        map[sourceOrgCode].userIds += `,${item.userId}`;
      } else {
        // 新分组，只包含两个目标字段
        map[sourceOrgCode] = {
          userIds: item.userId, // 原code → userIds
          sourceOrgCode, // 原parentCode → sourceOrgCode
        };
      }
      return map;
    }, {}),
  );
  if (res.length === 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  const data = {
    targetOrgCode: res?.[0]?.code,
    keepOriginal: isRetainOrg.value ? '1' : '0',
    items: result,
  };
  const response: any = await UserService.transferUsersOut(data);

  if (response) {
    // 清空选中状态
    userSelection.value = [];
    userOutputVisible.value = false;
    ElMessage.success(response.message || t('user.userOutputSuccess'));
    // 调用接口，用户列表数据
    fetchUserList();
  } else {
    ElMessage.error(response.message || t('user.userOutputFail'));
  }
}

/**
 * 取消用户转出至其他组织
 */
function cancelUserOutput() {
  userOutputVisible.value = false;
}

function handleUserRemove() {
  if (userSelection.value.length === 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  // 从本组织中移除
  userRemoveVisible.value = true;
}

/**
 * 从本组织中移除用户
 */
async function removeUserFromOrg() {
  const data = userSelection.value.map(user => ({
    userId: user.userId,
    orgCode: user.orgCode,
  }));
  const response: any = await UserService.removeUser(data);
  if (response) {
    // 清空选中状态
    userSelection.value = [];
    userRemoveVisible.value = false;
    ElMessage.success(response.message || t('user.userRemoveSuccess'));
    // 调用接口，用户列表数据
    fetchUserList();
  } else {
    ElMessage.error(response.message || t('user.userRemoveFail'));
  }
}

/**
 * 启用当前组织机构
 */
async function handleEnable() {
  if (userSelection.value.length <= 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  // 过滤出userId和userCode，返回 [{userId, orgCode},{userId, orgCode}]
  const items = userSelection.value.map(user => ({
    userId: user.userId,
    orgCode: user.orgCode,
  }));

  const data = {
    items,
    status: 1,
  };
  const response = await UserService.changUserStatus(data);
  if (response) {
    userSelection.value = [];
    fetchUserList();
    ElMessage.success(t('user.userStatusUpdateSuccess'));
  } else {
    ElMessage.error(t('user.userStatusUpdateFail'));
  }
}

/**
 * 停用当前组织机构
 */
async function handleDisable() {
  if (userSelection.value.length <= 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  const items = userSelection.value.map(user => ({
    userId: user.userId,
    orgCode: user.orgCode,
  }));

  const data = {
    items,
    status: 0,
  };
  const response = await UserService.changUserStatus(data);
  if (response) {
    userSelection.value = [];
    fetchUserList();
    ElMessage.success(t('user.userStatusUpdateSuccess'));
  } else {
    ElMessage.error(t('user.userStatusUpdateFail'));
  }
}

/**
 * 启用全部组织机构
 */
async function handleAllEnable() {
  if (userSelection.value.length <= 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  const ids = userSelection.value.map(user => user.userId).join(',');
  const data = {
    userIds: ids,
    status: 1,
  };
  const response = await UserService.changAllUserStatus(data);
  if (response) {
    userSelection.value = [];
    fetchUserList();
    ElMessage.success(t('user.userStatusUpdateSuccess'));
  } else {
    ElMessage.error(t('user.userStatusUpdateFail'));
  }
}

/**
 * 停用全部组织机构
 */
async function handleAllDisable() {
  if (userSelection.value.length === 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  const ids = userSelection.value.map(user => user.userId).join(',');
  const data = {
    userIds: ids,
    status: 0,
  };
  const response = await UserService.changAllUserStatus(data);
  if (response) {
    // 清空选中状态
    userSelection.value = [];
    fetchUserList();
    ElMessage.success(t('user.userStatusUpdateSuccess'));
  } else {
    ElMessage.error(t('user.userStatusUpdateFail'));
  }
}

/**
 * 下线
 */
function handleOffLine() {
  if (userSelection.value.length === 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  offlineVisible.value = true;
}

/**
 * 下线
 */
async function offLineUser() {
  const items = userSelection.value.map(user => ({
    userId: user.userId,
    orgCode: user.orgCode,
  }));
  const data = {
    items,
  };
  const response = await UserService.offlineUser(data);
  if (response) {
    // 清空选中状态
    userSelection.value = [];
    offlineVisible.value = false;
    fetchUserList();
    ElMessage.success(t('user.offlineSuccess'));
  } else {
    offlineVisible.value = false;
    ElMessage.error(t('user.offlineFail'));
  }
}

/**
 * 重置密码-弹窗
 */
function handleResetPassword() {
  if (userSelection.value.length === 0) {
    ElMessage.warning(t('user.selectTip'));
    return;
  }
  resetPasswordVisible.value = true;
}

/**
 * 关闭密码-弹窗
 */
function closeResetPassword() {
  resetPasswordVisible.value = false;
  copyPasswordVisible.value = false;
}

/**
 * 调用重置密码接口
 */
async function resetPassword() {
  const ids = computed(() => {
    return userSelection.value.map(user => user.userId).join(', ');
  });
  const data = {
    userId: ids.value,
  };
  const response = await UserService.resetPassword(data);
  if (response) {
    // 清空选中状态
    userSelection.value = [];
    // resetPasswordVisible.value = false;
    copyPasswordVisible.value = true;
    password.value = response.data;
    fetchUserList();
    ElMessage.success(t('user.resetPasswordSuccess'));
  }
}

/**
 * 复制密码
 */
async function copyPassword() {
  if (!password.value) {
    ElMessage.warning(t('user.passwordNull'));
    return;
  }
  try {
    await navigator.clipboard.writeText(password.value);
    ElMessage.success(t('user.copyPasswordSuccess'));
  } catch (err) {
    console.error(t('user.copyPasswordError'), err);
    ElMessage.error(t('user.copyPasswordError'));
  }
}

/**
 * 查看组织信息
 * @param row
 */
function handleOrgInfo(row: UserBO) {
  currentUser.value = row;
  orgVisible.value = true;
  // 调用接口根据用户信息，查询用户相关的组织信息
  fetchUserOrgInfo();
}

/**
 * 查询用户所属组织信息
 */
async function fetchUserOrgInfo() {
  const data = {
    userId: currentUser.value?.userId,
  };
  const res = await UserService.getUserOrgList(data);
  orgList.value = res || [];
}

/**
 * 加载补充信息接口
 * @param row
 */
async function handleInfo(row: UserBO) {
  currentUser.value = row;
  infoVisible.value = true;
  const data = {
    userId: currentUser.value.userId,
    orgCode: currentUser.value.orgCode,
  };
  const res = await UserService.getUserExtraInfo(data);
  infoData.value = res || '';
}

/**
 * 取消补充信息
 */
function cancelInfo() {
  infoVisible.value = false;
}

/**
 * 保存补充信息
 * @param res
 */
async function saveInfo(res: string) {
  infoVisible.value = false;
  const data = {
    userId: currentUser.value?.userId,
    orgCode: currentUser.value?.orgCode,
    extraInfo: res,
  };

  const response = await UserService.updateUserExtraInfo(data);

  if (response) {
    ElMessage.success(t('user.userExtendInfoSuccess'));
  } else {
    ElMessage.error(t('user.userExtendInfoErro'));
  }
}

async function handleRoles(row: UserBO) {
  const data = {
    userId: row.userId,
    orgCode: row.orgCode,
    current: 1,
    size: 10,
  };
  await fetchAssignRoleList(data);
  // await
  currentUser.value = Object.assign({}, row);
  rolesVisible.value = true;
}

function updateRoleList(params: { current: number, size: number }) {
  const data = {
    orgCode: currentUser.value?.orgCode,
    current: params.current,
    size: params.size,
    userId: currentUser.value?.userId,
    // search: params.search
  };
  fetchAssignRoleList(data);
}

function updateFullRoleList(params: { current: number, size: number }) {
  const data = {
    orgCode: currentUser.value?.orgCode,
    current: params.current,
    size: params.size,
    userId: currentUser.value?.userId,
    // search: params.search
  };
  getAssignableRoleList(data);
}

/**
 * 获取用户列表数据
 * @returns Promise<UserBO[]>
 */
async function fetchAssignRoleList(params: GetUserRoleListParams) {
  loading.value = true;
  const res = await UserRoleService.getUserAssignRoleList(params);
  rolesList.value = res.data.records;
  assignRolesPageInfo.total = Number(res.data.total);
  loading.value = false;
}

/**
 * 获取用户可分配角色
 * @returns Promise<UserBO[]>
 */
async function getAssignableRoleList(params: GetRoleListParams) {
  loading.value = true;
  const res = await UserRoleService.getAssignableRoleList(params);
  fullRolesList.value = res.data.records;
  fullRolePageInfo.total = Number(res.data.total);
  loading.value = false;
}

async function getRoleList(params: GetRoleListParams) {
  loading.value = true;
  const res = await UserRoleService.getRoleList(params);
  fullRolesList.value = res.data;
  loading.value = false;
}

async function deleteAssignRole(params: DeleteRoleParams) {
  loading.value = true;
  const res = await UserRoleService.deleteUserAssignRole(params);
  const data = {
    orgCode: currentUser.value?.orgCode,
    current: 1,
    size: 10,
    userId: currentUser.value?.userId,
  };
  if (res) {
    ElMessage.success('删除成功');
    updateRoleList(data);
  }
  loading.value = false;
}

async function addAssignRole(params: AddRoleParams) {
  loading.value = true;
  const res = await UserRoleService.addUserAssignRole({ ...params });
  const data = {
    orgCode: currentUser.value?.orgCode,
    current: 1,
    size: 10,
    userId: currentUser.value?.userId,
  };
  if (res) {
    ElMessage.success('新增成功');
    updateRoleList(data);
  }
  loading.value = false;
}

/**
 * 保存角色
 * @param _res
 */
function saveRoles(_res: any) {
  rolesVisible.value = false;
  // 调用保存角色接口
}

/**
 * 取消分配角色
 */
function cancelRoles() {
  rolesVisible.value = false;
}
</script>

<template>
  <div :class="styles['org-page-container']">
    <!-- 主体容器 -->
    <div :class="styles['org-mapping-container']">
      <!-- 左侧组织树区域 -->
      <div :class="styles['org-tree-container']">
        <!-- 搜索输入框 -->
        <ElInput
          v-model="filterText"
          :placeholder="t('user.seacherTreePlaceholder')"
          clearable
          :class="styles['search-input']"
        >
          <template #suffix>
            <LsIcon font-family="iconfont" value="icon-Search" :class="styles['icon-Search']" />
          </template>
        </ElInput>

        <!-- 搜索结果区域 -->
        <div v-show="filterStatus" :class="styles['org-filter-flat-results']">
          <div
            v-for="node in searchResults"
            :key="node.code"
            :class="[styles['result-item'], selectedSearchNode === node.code ? styles['result-item-active'] : '']"
            :title="`${node.code} ${node.label}`"
            @click="handleSelectSearchResult(node)"
          >
            <span :class="styles['result-label']" v-html="getHighLight(node.label, filterText)" />
          </div>
          <div v-if="searchResults.length === 0 && !loading" :class="styles['no-results']">
            {{ t('user.noData') }}
          </div>
          <div v-if="loading" :class="styles['loading-results']">
            {{ t('user.searching') }}
          </div>
        </div>

        <!-- 组织树 -->
        <div :class="styles['org-tree']">
          <ElTree
            v-show="!filterStatus"
            ref="treeRef"
            :props="props"
            lazy
            node-key="code"
            :current-node-key="currentNodeKey"
            highlight-current
            :load="loadNode"
            :expand-on-click-node="false"
            :default-expanded-keys="defaultExpandedKeys"
            @current-change="handleCurrentNodeChange"
          />
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div :class="styles['org-main-content']">
        <!-- 组织状态显示 -->
        <div :class="styles['org-status-section']">
          <span>{{ orgForm.orgName }}</span>
        </div>

        <!-- 组织信息表单区域 -->
        <div :class="styles['org-info-section']">
          <div :class="styles['info-title']">
            <span :class="styles['info-line']" />
            <span>{{ t('user.orgInfo') }}</span>
          </div>

          <ElForm :model="orgForm" label-width="120px" label-position="top">
            <ElRow :gutter="32">
              <ElCol :span="8">
                <ElFormItem :label=" `${t('user.orgCode')}`">
                  <ElInput v-model="orgForm.orgCode" disabled />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem :label=" `${t('user.orgName')}`">
                  <ElInput v-model="orgForm.orgFullName" disabled />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem :label=" `${t('user.abbreviation')}`">
                  <ElInput v-model="orgForm.orgName" disabled />
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
        </div>

        <!-- 用户表格区域 -->
        <div :class="styles['org-mapping-section']">
          <div :class="styles['info-title']">
            <span :class="styles['info-line']" />
            <span style="white-space: nowrap;">{{ t('user.info') }}</span>

            <!-- 操作按钮组 -->
            <div :class="styles['mapping-operation']">
              <ElInput
                v-model="keyWord"
                :class="styles['mapping-search-input']"
                :placeholder="t('user.seacherPlaceholder')"
                @change="fetchUserList"
              >
                <template #suffix>
                  <LsIcon font-family="iconfont" value="icon-Search" :class="styles['icon-Search']" />
                </template>
              </ElInput>
              <ElDivider direction="vertical" :class="styles['custom-vertical-divider']" />
              <ElButton :class="styles['button-border']" @click="handleUserInput">
                <span :class="styles['button-font']">{{ t('user.userInput') }}</span>
              </ElButton>

              <!-- 用户转出下拉 -->
              <ElDropdown>
                <ElButton
                  :class="styles['primary-border']"
                  :style="{ marginLeft: '12px' }"
                  @mouseenter="userOutputHovering = true"
                  @mouseleave="userOutputHovering = false"
                >
                  <span :class="styles['button-font']">{{ t('user.userOutput') }}</span>
                  <LsIcon font-family="iconfont" :value="userOutputHovering ? 'icon-PullUp' : 'icon-PullDown'" :class="styles['icon-small']" />
                </ElButton>
                <template #dropdown>
                  <ElDropdownMenu>
                    <ElDropdownItem @click="handleUserOut">
                      {{ t('user.outputToOther') }}
                    </ElDropdownItem>
                    <ElDropdownItem @click="handleUserRemove">
                      {{ t('user.remove') }}
                    </ElDropdownItem>
                  </ElDropdownMenu>
                </template>
              </ElDropdown>

              <!-- 启用下拉 -->
              <ElDropdown>
                <ElButton
                  :class="styles['primary-border']"
                  :style="{ marginLeft: '12px' }" @mouseenter="enabledHovering = true"
                  @mouseleave="enabledHovering = false"
                >
                  <span :class="styles['button-font']">{{ t('user.enabled') }}</span>
                  <LsIcon font-family="iconfont" :value="enabledHovering ? 'icon-PullUp' : 'icon-PullDown'" :class="styles['icon-small']" />
                </ElButton>
                <template #dropdown>
                  <ElDropdownMenu>
                    <ElDropdownItem @click="handleAllEnable">
                      {{ t('user.allOrg') }}
                    </ElDropdownItem>
                    <ElDropdownItem @click="handleEnable">
                      {{ t('user.currentOrg') }}
                    </ElDropdownItem>
                  </ElDropdownMenu>
                </template>
              </ElDropdown>

              <div :class="styles['mapping-operation-group']">
                <!-- 停用下拉 -->
                <ElDropdown>
                  <ElButton
                    :class="styles['primary-border']"
                    :style="{ marginRight: '12px', marginLeft: '12px' }" @mouseenter="disabledHovering = true"
                    @mouseleave="disabledHovering = false"
                  >
                    <span :class="styles['button-font']">{{ t('user.disabled') }}</span>
                    <LsIcon font-family="iconfont" :value="disabledHovering ? 'icon-PullUp' : 'icon-PullDown'" :class="styles['icon-small']" />
                  </ElButton>
                  <template #dropdown>
                    <ElDropdownMenu>
                      <ElDropdownItem @click="handleAllDisable">
                        {{ t('user.allOrg') }}
                      </ElDropdownItem>
                      <ElDropdownItem @click="handleDisable">
                        {{ t('user.currentOrg') }}
                      </ElDropdownItem>
                    </ElDropdownMenu>
                  </template>
                </ElDropdown>

                <!-- 下线按钮 -->
                <ElButton :class="styles['button-border']" @click="handleOffLine">
                  <span :class="styles['button-font']">{{ t('user.offline') }}</span>
                </ElButton>
                <!-- 重置密码 -->
                <ElButton :class="styles['button-border']" @click="handleResetPassword">
                  <span :class="styles['button-font']">{{ t('user.resetPassword') }}</span>
                </ElButton>
              </div>

              <div :class="styles['mapping-operation-group-menu']">
                <el-menu
                  mode="horizontal"
                  :ellipsis="false"
                  :class="styles['mapping-horizontal-menu']"
                  background-color="transparent"
                  :collapse-transition="false"
                  popper-class="mapping-horizontal-menu-popper"
                >
                  <el-sub-menu index="1" @mouseenter="moreHoveringMap['more-menu-group'] = true" @mouseleave="moreHoveringMap['more-menu-group'] = false">
                    <template #title>
                      <span :class="styles['button-font']">{{ t('user.more') }}</span>
                      <LsIcon font-family="iconfont" :value="moreHoveringMap['more-menu-group'] ? 'icon-PullUp' : 'icon-PullDown'" :class="styles['icon-small']" />
                    </template>
                    <el-sub-menu index="1-1">
                      <template #title>
                        <span :class="styles['button-font']">{{ t('user.disabled') }}</span>
                      </template>
                      <el-menu-item index="1-1-1" @click="handleAllDisable">
                        {{ t('user.allOrg') }}
                      </el-menu-item>
                      <el-menu-item index="1-1-2" @click="handleDisable">
                        {{ t('user.currentOrg') }}
                      </el-menu-item>
                    </el-sub-menu>
                    <el-menu-item index="1-2" @click="handleOffLine">
                      {{ t('user.offline') }}
                    </el-menu-item>
                    <el-menu-item index="1-3" @click="handleResetPassword">
                      {{ t('user.resetPassword') }}
                    </el-menu-item>
                  </el-sub-menu>
                </el-menu>
              </div>
            </div>
          </div>

          <!-- 用户表格 -->
          <ElTable
            :data="userList"
            style="width: 100%; height: 100%;"
            header-cell-class-name="table-header"
            :resizable="true"
            :border="true"
            @selection-change="handleSelectionChange"
          >
            <template #empty>
              <empty />
            </template>
            <ElTableColumn fixed="left" type="selection" width="40" />
            <ElTableColumn :prop="UserTableColProp.INDEX" :label="t('common.serialNumber')" width="50" />
            <ElTableColumn :prop="UserTableColProp.USER_ID" :label="t('user.userId')" min-width="120" />
            <ElTableColumn :prop="UserTableColProp.USER_NAME" :label="t('user.userName')" min-width="100" />
            <ElTableColumn :prop="UserTableColProp.GENDER" :label="t('user.gender')" width="50">
              <template #default="{ row }">
                <span>{{ row.gender === UserGender.USER_MAN ? t('user.man') : t('user.woman') }}</span>
              </template>
            </ElTableColumn>
            <ElTableColumn :prop="UserTableColProp.ORG_CODE" :label="t('user.orgCode')" min-width="120" />
            <ElTableColumn :prop="UserTableColProp.ORG_SHORT_NAME" :label="t('user.orgShortName')" min-width="120" />
            <ElTableColumn :prop="UserTableColProp.EMAIL" :label="t('user.email')" column-key="email" min-width="200">
              <template #default="scope">
                <ElTooltip
                  :content="scope.row.email"
                  placement="top"
                  effect="light"
                >
                  <div :class="styles['ellipsis-text']">
                    {{ scope.row.email }}
                  </div>
                </ElTooltip>
              </template>
            </ElTableColumn>
            <!-- <ElTableColumn prop="mobilePhone" :label="t('user.mobilePhone')" min-width="120" /> -->
            <ElTableColumn :prop="UserTableColProp.STATUS" :label="t('user.status')" width="120">
              <template #default="{ row }">
                <div :class="[styles['status-dot'], row.status === UserStatus.USER_SUCCESS ? styles.success : styles.danger]" />
                <span>{{ row.status === UserStatus.USER_SUCCESS ? t('user.normal') : t('user.disabled') }}</span>
              </template>
            </ElTableColumn>
            <ElTableColumn :prop="UserTableColProp.CREATE_NAME" :label="t('common.createBy')" min-width="120" />
            <ElTableColumn :prop="UserTableColProp.CREATE_TIME" :label="t('common.createTime')" min-width="180" :formatter="formatDateTime" />
            <ElTableColumn :prop="UserTableColProp.UPDATE_NAME" :label="t('common.updateBy')" min-width="120" />
            <ElTableColumn :prop="UserTableColProp.UPDATE_TIME" :label="t('common.updateTime')" min-width="180" :formatter="formatDateTime" />
            <!-- 操作列 -->
            <ElTableColumn fixed="right" :label="t('common.operation')" width="180" class-name="operation-table-column">
              <template #default="{ row }">
                <ElButton
                  link
                  type="primary"
                  size="small"
                  @click.prevent="handleRoles(row)"
                >
                  <span :class="styles['button-font']">{{ t('user.assignRoles') }}</span>
                </ElButton>
                <ElDivider direction="vertical" />
                <ElDropdown>
                  <ElButton link @mouseenter="moreHoveringMap[`${row.userId}${row.orgCode}`] = true" @mouseleave="moreHoveringMap[`${row.userId}${row.orgCode}`] = false">
                    <span :class="styles['button-font']">{{ t('user.more') }}</span>
                    <LsIcon font-family="iconfont" :value="moreHoveringMap[`${row.userId}${row.orgCode}`] ? 'icon-PullUp' : 'icon-PullDown'" :class="styles['icon-small']" />
                  </ElButton>
                  <template #dropdown>
                    <ElDropdownMenu>
                      <ElDropdownItem @click.prevent="handleOrgInfo(row)">
                        {{ t('user.showOrgInfo') }}
                      </ElDropdownItem>
                      <ElDropdownItem @click.prevent="handleInfo(row)">
                        {{ t('user.userExtendInfo') }}
                      </ElDropdownItem>
                    </ElDropdownMenu>
                  </template>
                </ElDropdown>
              </template>
            </ElTableColumn>
          </ElTable>

          <!-- 分页区域 -->
          <div :class="styles['pagination-container']">
            <ElPagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 用户转入弹窗 -->
  <OrgUserTransfer
    :request-params="requestParams"
    :close-on-click-modal="false"
    :tree-data-type="OrgUserTransfer_TreeDataType.User"
    :user-type="OrgUserTransfer_UserType.OrgUser"
    :disable-orgs="orgForm.orgCode"
    :multiple="true"
    :visible="userInputVisible"
    :value="userVal"
    :title="t('user.userInput')"
    :input-placeholder="t('user.userPlaceholder')"
    @confirm="saveUserInput"
    @cancel="cancelUserInput"
  >
    <template #placeholder>
      <div :class="styles['slot-placeholder-right-bottom']">
        <ElCheckbox v-model="isRetainOrg">
          {{ t('user.isRetainOrg') }}
        </ElCheckbox>
      </div>
    </template>
  </OrgUserTransfer>

  <!-- 用户转出至其他组织弹窗 -->
  <OrgUserTransfer
    :request-params="requestParams"
    :tree-data-type="OrgUserTransfer_TreeDataType.Org"
    close-on-click-modal="false"
    url="/api/v1/extend-org/load"
    query-url="/api/v1/extend-org/load"
    :input-placeholder="t('user.orgPlaceholder')"
    :multiple="false"
    :visible="userOutputVisible"
    :title="t('user.outputToOther')"
    :value="userVal"
    @confirm="saveUserOutput"
    @cancel="cancelUserOutput"
  >
    <template #placeholder>
      <div :class="styles['slot-placeholder-right-bottom']" class="placeholder-checkbox-container">
        <ElCheckbox v-model="isRetainOrg">
          {{ t('user.isRetainOrg') }}
        </ElCheckbox>
      </div>
    </template>
  </OrgUserTransfer>

  <!-- 用户转出-从本组织移除弹窗 -->
  <ElDialog
    v-model="userRemoveVisible"
    :close-on-click-modal="false"
    :class="styles['overide-animation']"
    width="353"
    :style="{ top: '0px', right: '0px' }"
    :title="t('user.tip')"
  >
    <span :class="styles['delete-container']">{{ t('user.removeTip') }}</span>
    <template #footer>
      <div :class="styles['dialog-footer']">
        <ElButton :class="styles['gray-button']" @click="userRemoveVisible = false">
          {{ t('common.cancel') }}
        </ElButton>
        <ElButton :class="styles['primary-button']" @click="removeUserFromOrg">
          {{ t('user.continue') }}
        </ElButton>
      </div>
    </template>
  </ElDialog>
  <!--  下线弹窗  -->
  <ElDialog
    v-model="offlineVisible"
    :close-on-click-modal="false"
    :class="styles['overide-animation']"
    width="353"
    :style="{ top: '0px', right: '0px' }"
    :title="t('user.tip')"
  >
    <span :class="styles['delete-container']">{{ `${t('user.sureOffline')} ${userSelection?.length || 0} ${t('user.offlineUserTip')}` }}</span>
    <template #footer>
      <div :class="styles['dialog-footer']">
        <ElButton :class="styles['gray-button']" @click="offlineVisible = false">
          {{ t('common.cancel') }}
        </ElButton>
        <ElButton :class="styles['primary-button']" @click="offLineUser">
          {{ t('user.ok') }}
        </ElButton>
      </div>
    </template>
  </ElDialog>
  <!--  重置密码  -->
  <ElDialog
    v-model="resetPasswordVisible"
    :close-on-click-modal="false"
    :class="styles['overide-animation']"
    width="353"
    :style="{ top: '0px', right: '0px' }"
    :title="t('user.tip')"
    @close="closeResetPassword"
  >
    <span :class="styles['delete-container']">
      {{ copyPasswordVisible ? t('user.resetPasswordSuccess') : t('user.resetPasswordTip') }}
    </span>
    <div :class="styles['delete-container']">
      {{ copyPasswordVisible ? `${t('user.newPassword')} ${password} ` : `${userSelection.map(user => user.userName).join(', ')}` }}
    </div>
    <template #footer>
      <div :class="styles['dialog-footer']">
        <ElButton v-if="copyPasswordVisible" :class="styles['primary-button']" @click="copyPassword">
          {{ t('user.copyPassword') }}
        </ElButton>
        <div v-else>
          <ElButton :class="styles['gray-button']" @click="resetPasswordVisible = false">
            {{ t('common.cancel') }}
          </ElButton>
          <ElButton :class="styles['primary-button']" @click="resetPassword">
            {{ t('user.reset') }}
          </ElButton>
        </div>
      </div>
    </template>
  </ElDialog>

  <!-- 查看组织弹窗 -->
  <ElDialog
    v-model="orgVisible"
    :close-on-click-modal="false"
    :class="styles['overide-animation']"
    destroy-on-close
    width="1010"
    :style="{ height: '600px' }"
    :title="t('user.showOrgInfo')"
    @close="orgVisible = false"
  >
    <UserOrgInfo :org-list="orgList" />
  </ElDialog>

  <!-- 分配角色弹窗 -->
  <UserRoles
    :roles-visible="rolesVisible" :page-data="assignRolesPageInfo" :user="currentUser" :roles-list="rolesList"
    :full-roles-list="fullRolesList" :get-role-list="getRoleList" :get-assignable-role-list="getAssignableRoleList"
    :full-role-page-info="fullRolePageInfo" @save="saveRoles" @cancel="cancelRoles"
    @fetch-assign-role-list="updateRoleList" @fetch-full-assign-role-list="updateFullRoleList"
    @delete-assign-role="deleteAssignRole" @add-assign-role="addAssignRole"
  />

  <!-- 补充信息弹窗 -->
  <ElDialog
    v-model="infoVisible"
    :close-on-click-modal="false"
    :class="styles['overide-animation']"
    destroy-on-close
    width="400"
    height="362"
    :title="t('user.userExtendInfo')"
  >
    <UserExtendInfo
      :data-str="infoData"
      :edit-mode="false"
      @save="saveInfo"
      @close="cancelInfo"
    />
  </ElDialog>
</template>
